package com.gs.wzweather.test.convertword;

import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;

import java.io.File;

/**
 * Created with IntelliJ IDEA.
 * User: Legolas
 * Date: 2017/10/25 0025
 */

class MyFileListener extends FileAlterationListenerAdaptor {

    String rootDir;

    public MyFileListener() {

    }

    public MyFileListener(String dir) {
        this.rootDir = dir;
    }

    @Override
    public void onFileCreate(File file) {
        String fileName = file.getName();
        String aimName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";
        String aimPath = rootDir + "pdf\\";
        File aimDir = new File(aimPath);
        if (!aimDir.exists()) {
            aimDir.mkdir();
        }
        File aimFile = new File(aimPath + aimName);
        if (!aimFile.exists()) {
            Docx4jToPdf.convert(file, aimFile);
            System.out.println("[新建pdf]:" + aimFile);
        }

    }

    @Override
    public void onFileChange(File file) {
        String fileName = file.getName();
        String aimName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";
        String aimPath = rootDir + "pdf\\";
        File aimDir = new File(aimPath);
        File aimFile = new File(aimPath + aimName);
        if (!aimDir.exists()) {
            aimDir.mkdir();
        }
        if (aimFile.exists()) {
            aimFile.delete();
            Docx4jToPdf.convert(file, aimFile);
            System.out.println("[更新pdf]:" + aimFile);
        }
    }

    @Override
    public void onFileDelete(File file) {
        String fileName = file.getName();
        String aimName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";
        String aimPath = rootDir + "pdf\\";
        File aimDir = new File(aimPath);
        if (!aimDir.exists()) {
            aimDir.mkdir();
        }
        File aimFile = new File(aimPath + aimName);
        if (aimFile.exists()) {
            aimFile.delete();
            System.out.println("[删除pdf]:" + aimFile);
        }
    }
}
